package blog.caidabao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**range
     *按照score的值降序排列
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<ZSetOperations.TypedTuple<Integer>> revrangeWithScore(String key,int start,int end) {
        return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
    }

    /**
     * 文章阅读量增加
     * @param id
     */
    public void articleViewTimesIncr(Integer id){
        this.redisTemplate.opsForZSet().incrementScore("article_range",id,1);
    }

    /**
     * 根据文章id查询阅读量
     * @param id
     * @return
     */
    public Double getArticleViewTimes(Integer id) {
        return this.redisTemplate.opsForZSet().score("article_range",id);
    }

    /**
     *文章阅读量添加数据库
     */
    public void addArticleViewTimes(Integer articleId) {
        Boolean result = this.redisTemplate.opsForZSet().add("article_range", articleId, 0);
    }

    /**
     * 根据文章id删除文章阅读量数据
     * @param articleId
     */
    public void deleteArticle(Integer articleId){
        long result=this.redisTemplate.opsForZSet().remove("article_range",articleId);
    }
}
